/**
* @description: 待办工单 -》 通信电源巡视 -》 通信电源信息完善
**/

<template>
  <div class="complete-wrap">
    <nav-bar class="header" back :title="isUpdate ? '完善电源信息' : '新增电源信息'" @goBack="goBack" />
    <div class="main-container">
      <van-form ref="ruleForm">

        <plateTitle title="基本信息" :isRequired="false" class="plate-title" />

        <div class="base-info-container">
          <van-cell-group v-for="(item, index) in currentData.visibleProps" :key="index">
            <!-- 不可编辑框 -->
            <van-field v-model="item.value" v-if="item.elementType === 'TEXT'" :required="item.isRequired" readonly input-align="right" :value="item.value" :label="item.title" @click="checkInfo(item)"
                       :name="item.name" :rules="item.rules" error-message-align="right" />
            <!-- 弹出筛选框 -->
            <van-field v-if="item.elementType === 'PICKER'" :required="item.isRequired" readonly clickable input-align="right" right-icon="arrow" v-model="item.text" :label="item.title"
              placeholder="点击选择" @click="checkPickerList(item)"  :name="item.name" :rules="item.rules" error-message-align="right" />
            <!-- 弹出日期筛选框 -->
            <van-field v-if="item.elementType === 'TIMEPICKER'" :required="item.isRequired" readonly clickable input-align="right" right-icon="arrow" v-model="item.text" :label="item.title"
              placeholder="点击选择" @click="checkPickerList(item)"  :name="item.name" :rules="item.rules" error-message-align="right"  />
            <!-- 输入框 -->
            <van-field v-if="item.elementType === 'INPUT'" :required="item.isRequired" clickable input-align="right" :value="item.value" :label="item.title" placeholder="请输入"
              @input="inputBlur($event, item)"  :name="item.name" :rules="item.rules" error-message-align="right"  />
            <!-- 输入带扫码 -->
            <van-field v-if="item.elementType === 'INPUT&SCAN'" :required="item.isRequired" input-align="right" right-icon="scan" @input="inputBlur($event, item)" @click-right-icon="scanQrcode(item)"
              :value="item.value" :label="item.title" />

          </van-cell-group>
        </div>
        <view v-if="isUpdate && currentData.hideProps.serviceState === 4">
          <plateTitle title="巡视信息" :isRequired="false" class="plate-title-2" />
          <!-- 巡视照片 -->
          <view class="patrol-info-container">
            <view>巡视照片</view>
            <van-divider dashed />
            <div class="image-wrap">
              <div class="image-list">
                <div
                  class="upload-button"
                  v-for="(imgItem, index) in files"
                  :style="{'background-image': `url(${imgItem.bgImg})`}"
                  @click.stop="imageHandle(imgItem, index, 'CHOOSE')"
                >
                  <div v-if="imgItem.img" class="delete-icon" @click.stop="imageHandle(imgItem, index, 'DELETE')">×</div>
                  <img v-if="imgItem.img" :src="imgItem.img" alt="" @click.stop="imageHandle(imgItem, index, 'PREVIEW')">
                </div>
              </div>
            </div>
          </view>
          <!-- 备注 -->
          <view class="remark-info-container">
            <view>备注</view>
            <van-divider dashed />
            <div class="remark-wrap">
              <textarea class="remark-text" v-model="currentData.otherProps.remark">
            </textarea>
            </div>
          </view>

          <view class="result-info-container">
            <van-cell-group v-for="(item, index) in currentData.tourInfoProps" :key="index">
              <!-- 不可编辑框 -->
              <van-field v-if="item.elementType === 'TEXT'" :required="item.isRequired" readonly input-align="right" :value="item.value" :label="item.title" />
            </van-cell-group>
          </view>
        </view>

        <van-button block @click="upload">保存</van-button>
      </van-form>
      <!--选择器-->
      <van-popup v-model="showPicker" position="bottom">
        <van-picker
          ref="picker"
          :default-index="defaultPickerIndex"
          show-toolbar
          :columns="currentPickerList"
          cancel-button-text="清空"
          @confirm="pickerConfirm"
          @cancel="pickerEmpty"
          @change="pickerChange"
        />
        <van-field
          v-show="showCustomInput"
          v-model="customInput"
          placeholder="请输入"
          :border="true"
        />
      </van-popup>
      <!--时间选择器-->
      <van-popup v-model="showTimePicker" position="bottom">
        <van-datetime-picker
            v-model="currentDate"
            type="year-month"
            title="选择年月"
            :formatter="formatter"
            :min-date="minDate"
            show-toolbar
            cancel-button-text="清空"
            @confirm="pickerConfirm"
            @cancel="pickerEmpty"
        />
      </van-popup>

      <van-popup class="van-preview-wrap" v-model="showPreview" @click="showPreview = false">
        <van-swipe>
          <div v-for="(image, index) in files" :key="index">
            <van-swipe-item v-if="image.img" style="text-align: center;">
              <div style="width: 100%; text-align: center;">{{ image.previewName }}</div>
              <img :src="image.img" />
            </van-swipe-item>
          </div>
        </van-swipe>
      </van-popup>
    </div>
  </div>
</template>

<script>
import {Dialog, Toast} from "vant";

let infoMap_add = {
  hideProps: {
    taskId: '', //所属工单id    //必填
    siteid: '', //所属站点
    sitename: '',
    tourOperId: '', //巡检人ID  必填      userId放进来
    tourOperName: '', //巡检人名称    必填       userName放进来
    tourTim: '', //巡检时间 必填
    remark: '', //备注
    powerModelnumberCustom: '', // 自定义通信电源型号
    powerTechTypeCustom: '', // 自定义通信电源制造厂商
    accumModelnumberCustom: '', // 自定义配套蓄电池组型号
    accumProducerCustom: '', // 自定义配套蓄电池组制造厂商
    powerRectificationCustom: '', // 自定义整流模块型号
  },
  visibleProps: {
    // 显示的属性
    // "equName": {
    //   title: "通信电源名称",
    //   keys: "equName",
    //   value: "1#",
    //   isRequired: true,
    //   elementType: "TEXT"
    // }, //设备名称
    "sitename": {
      title: '所属站点',
      keys: 'sitename',
      value: '',
      isRequired: true,
      elementType: "TEXT",
      name:'sitename',
      rules:[{ required: true, trigger:'onSubmit'}]
    },   //所属站点名称
    "parRoom": {
      title: "所属机房",
      keys: "parRoom",
      value: "",
      text: "",
      isRequired: false,
      elementType: 'PICKER',
      optionsParams: { type: 'room' } // 获取options需要的参数
    }, //所属机房
    parRack: {
      title: '所属机柜编号',
      keys: 'parRack',
      value: '',
      isRequired: true,
      elementType: "INPUT",
      name:'parRack',
      rules:[{ required: true, trigger:'onSubmit'}]
    },   //所属机柜编号
    "parRackScreen": {
      title: "所属机柜屏眉",
      keys: "parRackScreen",
      value: "",
      isRequired: true,
      elementType: 'INPUT',
      name:'parRackScreen',
      rules:[{ required: true, trigger:'onSubmit'}]
    }, //所属机柜屏眉
    "serilanum": {
      title: "通信电源顺序",
      keys: "serilanum",
      value: "",
      text: "",
      isRequired: true,
      elementType: "PICKER",
      optionsParams: {type: "seril"}, // 获取options需要的参数
      name:'serilanum',
      rules:[{ required: true, trigger:'onSubmit'}]
    },    //通信电源顺序
    "entityid": {
      title: "实物ID",
      keys: "entityid",
      value: "",
      isRequired: false,
      elementType: 'INPUT&SCAN'
    }, //实物ID
    "powerTechType": {
      title: '通信电源制造厂商',
      keys: 'powerTechType',
      value: '',
      text: '',
      isRequired: true,
      elementType: 'PICKER',
      name:'powerTechType',
      rules:[{ required: true, trigger:'onSubmit'}],
      optionsParams: { type: 'powerProducer' } // 获取options需要的参数
    }, //通信电源制造厂商
    "powerModelnumber": {
      title: '通信电源型号',
      keys: 'powerModelnumber',
      value: '',
      text: '',
      isRequired: false,
      elementType: "PICKER",
      optionsParams: {type: "powerModel"}, // 获取options需要的参数
    },    //通信电源型号
    "powerFullCapacity": {
      title: "满配整流容量(A)",
      keys: "powerFullCapacity",
      value: "",
      text: "",
      isRequired: true,
      elementType: "INPUT",
      name:'powerFullCapacity',
      rules:[{ required: true, trigger:'onSubmit'}],

    },//满配整流容量(A)
    "powerPresentCapacity": {
      title: "当前配置整流容量(A)",
      keys: "powerPresentCapacity",
      value: "",
      text: "",
      isRequired: true,
      elementType: 'INPUT',
      name:'powerPresentCapacity',
      rules:[{ required: true, trigger:'onSubmit'}],
    }, //当前配置整流容量(A)
    powerRectification: {
      title: '整流模块型号',
      keys: 'powerRectification',
      value: '',
      text: '',
      isRequired: false,
      elementType: 'PICKER',
      optionsParams: { type: 'rectificationModel' } // 获取options需要的参数
    }, //整流模块型号
    powerSingle: {
      title: '单个整流模块容量(A)',
      keys: 'powerSingle',
      value: '',
      text: '',
      isRequired: false,
      elementType: 'INPUT'
    }, //单个整流模块容量(A)
    powerBegTim: {
      title: '通信电源投运时间',
      keys: 'powerBegTim',
      value: '',
      text: '',
      isRequired: false,
      elementType: "TIMEPICKER"
    },   //通信电源投运时间
    "accumProducer": {
      title: "配套蓄电池组制造厂商",
      keys: "accumProducer",
      value: "",
      isRequired: true,
      elementType: "PICKER",
      optionsParams: {type: "accumProducer"}, // 获取options需要的参数
      name:'accumProducer',
      rules:[{ required: true, trigger:'onSubmit'}],
    },       //配套蓄电池组制造厂商
    "accumModelnumber": {
      title: "配套蓄电池组型号",
      keys: "accumModelnumber",
      value: "",
      isRequired: false,
      elementType: "PICKER",
      optionsParams: {type: "accumModel"}, // 获取options需要的参数
    },          //配套蓄电池组型号
    "accumType": {
      title: "配套蓄电池类型",
      keys: "accumType",
      value: "",
      isRequired: false,
      elementType: 'PICKER',
      optionsParams: { type: 'accumType' } // 获取options需要的参数
    }, //配套蓄电池类型
    accumNum: {
      title: '配套蓄电池组数量',
      keys: 'accumNum',
      value: '',
      isRequired: false,
      elementType: "INPUT"
    },          //配套蓄电池组数量
    "accumBegTim": {
      title: "蓄电池组投运时间",
      keys: "accumBegTim",
      value: "",
      isRequired: false,
      elementType: 'TIMEPICKER'
    }, //蓄电池组投运时间
    runState: {
      title: "运行状态",
      keys: "runState",
      value: "",
      text: "",
      isRequired: true,
      elementType: "PICKER",
      optionsParams: {type: "runState"}, // 获取options需要的参数
    },   //运行状态
    accumCapacity: {
      title: '每组蓄电池容量(Ah)',
      keys: 'accumCapacity',
      value: '',
      isRequired: true,
      elementType: 'INPUT',
      name:'accumCapacity',
      rules:[{ required: true, trigger:'onSubmit'}],
    }, //每组蓄电池容量(Ah)
    powerLoadCurrent: {
      title: '当前负载电流(A)',
      keys: 'powerLoadCurrent',
      value: '',
      isRequired: true,
      elementType: 'INPUT',
      name:'powerLoadCurrent',
      rules:[{ required: true, trigger:'onSubmit'}],
    }, //当前负载电流(A)
    accumSumCapacity: {
      title: '蓄电池实测总容量(Ah)',
      keys: 'accumSumCapacity',
      value: '',
      isRequired: false,
      elementType: 'INPUT'
    }, //蓄电池实测总容量(Ah)
  }
}

let infoMap_update = {
  hideProps: {
    taskId: '', //所属工单id    //必填
    siteid: '', //所属站点
    sitename: '',
    tourOperId: '', //巡检人ID  必填      userId放进来
    powerModelnumberCustom: '', // 自定义通信电源型号
    powerTechTypeCustom: '', // 自定义通信电源制造厂商
    accumModelnumberCustom: '', // 自定义配套蓄电池组型号
    accumProducerCustom: '', // 自定义配套蓄电池组制造厂商
    powerRectificationCustom: '', // 自定义整流模块型号
  },
  visibleProps: {
    // 显示的属性
    equName: {
      title: '通信电源名称',
      keys: 'equName',
      value: '',
      isRequired: true,
      elementType: 'TEXT',
      name:'equName',
      rules:[{ required: true, trigger:'onSubmit'}],
    }, //设备名称
    "sitename": {
      title: "所属站点",
      keys: "sitename",
      value: "",
      isRequired: true,
      elementType: "TEXT",
      name:'sitename',
      rules:[{ required: true, trigger:'onSubmit'}],
    },   //所属站点名称
    "parRoom": {
      title: "所属机房",
      keys: "parRoom",
      value: "",
      text: "",
      isRequired: false,
      elementType: "PICKER",
      optionsParams: {type: "room"}, // 获取options需要的参数
    },   //所属机房
    "parRack": {
      title: "所属机柜编号",
      keys: "parRack",
      value: "",
      isRequired: true,
      elementType: "INPUT",
      name:'parRack',
      rules:[{ required: true, trigger:'onSubmit'}],

    },   //所属机柜编号
    "parRackScreen": {
      title: "所属机柜屏眉",
      keys: "parRackScreen",
      value: "",
      isRequired: true,
      elementType: 'INPUT',
      name:'parRackScreen',
      rules:[{ required: true, trigger:'onSubmit'}],
    }, //所属机柜屏眉
    "serilanum": {
      title: "通信电源顺序",
      keys: "serilanum",
      value: "",
      text: "",
      isRequired: true,
      elementType: "PICKER",
      optionsParams: {type: "seril"}, // 获取options需要的参数
      name:'serilanum',
      rules:[{ required: true, trigger:'onSubmit'}],
    },    //通信电源顺序
    "entityid": {
      title: "实物ID",
      keys: "entityid",
      value: "",
      isRequired: false,
      elementType: 'INPUT&SCAN'
    }, //实物ID
    powerTechType: {
      title: '通信电源制造厂商',
      keys: 'powerTechType',
      value: '',
      text: '',
      isRequired: true,
      elementType: 'PICKER',
      optionsParams: { type: 'powerProducer' }, // 获取options需要的参数
      name:'powerTechType',
      rules:[{ required: true, trigger:'onSubmit'}],
    }, //通信电源制造厂商
    powerModelnumber: {
      title: '通信电源型号',
      keys: 'powerModelnumber',
      value: '',
      text: '',
      isRequired: false,
      elementType: "PICKER",
      optionsParams: {type: "powerModel"}, // 获取options需要的参数
    },    //通信电源型号
    "powerFullCapacity": {
      title: "满配整流容量(A)",
      keys: "powerFullCapacity",
      value: "",
      text: "",
      isRequired: true,
      elementType: "INPUT",
      name:'powerFullCapacity',
      rules:[{ required: true, trigger:'onSubmit'}],

    },//满配整流容量(A)
    "powerPresentCapacity": {
      title: "当前配置整流容量(A)",
      keys: "powerPresentCapacity",
      value: "",
      text: "",
      isRequired: true,
      elementType: 'INPUT',
      name:'powerPresentCapacity',
      rules:[{ required: true, trigger:'onSubmit'}],
    }, //当前配置整流容量(A)
    powerRectification: {
      title: '整流模块型号',
      keys: 'powerRectification',
      value: '',
      text: '',
      isRequired: false,
      elementType: 'PICKER',
      optionsParams: { type: 'rectificationModel' } // 获取options需要的参数
    }, //整流模块型号
    powerSingle: {
      title: '单个整流模块容量(A)',
      keys: 'powerSingle',
      value: '',
      text: '',
      isRequired: false,
      elementType: 'INPUT'
    }, //单个整流模块容量(A)
    powerBegTim: {
      title: '通信电源投运时间',
      keys: 'powerBegTim',
      value: '',
      text: '',
      isRequired: false,
      elementType: "TIMEPICKER"
    },   //通信电源投运时间
    "accumProducer": {
      title: "配套蓄电池组制造厂商",
      keys: "accumProducer",
      value: "",
      isRequired: true,
      elementType: "PICKER",
      optionsParams: {type: "accumProducer"}, // 获取options需要的参数
      name:'accumProducer',
      rules:[{ required: true, trigger:'onSubmit'}],
    },       //配套蓄电池组制造厂商
    "accumModelnumber": {
      title: "配套蓄电池组型号",
      keys: "accumModelnumber",
      value: "",
      isRequired: false,
      elementType: "PICKER",
      optionsParams: {type: "accumModel"}, // 获取options需要的参数
    },          //配套蓄电池组型号
    "accumType": {
      title: "配套蓄电池类型",
      keys: "accumType",
      value: "",
      isRequired: false,
      elementType: 'PICKER',
      optionsParams: { type: 'accumType' } // 获取options需要的参数
    }, //配套蓄电池类型
    accumNum: {
      title: '配套蓄电池组数量',
      keys: 'accumNum',
      value: '',
      isRequired: false,
      elementType: "INPUT"
    },          //配套蓄电池组数量
    "accumBegTim": {
      title: "蓄电池组投运时间",
      keys: "accumBegTim",
      value: "",
      isRequired: false,
      elementType: 'TIMEPICKER'
    }, //蓄电池组投运时间
    runState: {
      title: "运行状态",
      keys: "runState",
      value: "",
      text: "",
      isRequired: true,
      elementType: "PICKER",
      optionsParams: {type: "runState"}, // 获取options需要的参数
    },   //运行状态
    accumCapacity: {
      title: '每组蓄电池容量(Ah)',
      keys: 'accumCapacity',
      value: '',
      isRequired: true,
      elementType: 'INPUT',
      name:'accumCapacity',
      rules:[{ required: true, trigger:'onSubmit'}],
    }, //每组蓄电池容量(Ah)
    powerLoadCurrent: {
      title: '当前负载电流(A)',
      keys: 'powerLoadCurrent',
      value: '',
      isRequired: true,
      elementType: 'INPUT',
      name:'powerLoadCurrent',
      rules:[{ required: true, trigger:'onSubmit'}],
    }, //当前负载电流(A)
    accumSumCapacity: {
      title: '蓄电池实测总容量(Ah)',
      keys: 'accumSumCapacity',
      value: '',
      isRequired: false,
      elementType: 'INPUT'
    }, //蓄电池实测总容量(Ah)
  },
  tourInfoProps: {
    // 显示的属性。包含巡视人和巡视时间
    tourOperName: {
      title: '巡视人',
      keys: 'tourOperName',
      value: '',
      isRequired: false,
      elementType: 'TEXT'
    }, //设备名称
    tourTim: {
      title: '巡视时间',
      keys: 'tourTim',
      value: '',
      isRequired: false,
      elementType: 'TEXT'
    } //所属站点名称
  },
  otherProps: {
    // 其他，如备注，照片等
    remark: '' //备注
  }
}

let fileTemplate = [
  {
    name: "EQUIPMENT.jpg",
    previewName: "设备照片",
    type: "EQUIPMENT",
    bgImg: require("../../../../static/img/bg_shebei.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
  {
    name: "NAMEPLATE.jpg",
    previewName: "分配屛照片",
    type: "NAMEPLATE",
    bgImg: require("../../../../static/img/bg_fenpeiping.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
  {
    name: "OTHER.jpg",
    previewName: "分配屛照片",
    type: "OTHER",
    bgImg: require("../../../../static/img/bg_fenpeiping.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
];
import config from "../../../../common/config";
import navBar from '../../../../components/common/nav-bar'
import plateTitle from '../../../../components/business/plateTitle'
import selectSite from '../../../common/selectSite'
import { mapGetters } from 'vuex'
import moment from 'moment'
import axios from 'axios'
import { merge } from "lodash";
import wx from "../../../../static/common_js/jweixin_1.0.0";
export default {
  components: { navBar, plateTitle, selectSite },
  data() {
    return {
      currentIndex: 0,
      baseUrl: "", // 基础url
      objId: '',
      taskId: '', // 工单id
      taskSiteId: '', // 站点id
      taskSiteName: '', // 站点name
      type: '', // 新增/完善
      taskType: '', //巡视进度跳转携带状态
      isUpdate: false,
      currentDate: "",
      minDate: new Date(0),
      showPicker: false,
      showTimePicker: false,
      showCustomInput: false, // 是否在下拉框中显示自定义输入
      customInput: '', // 下拉框中自定义输入的内容
      currentData: {}, // 当前数据，分为两种  添加和完善
      currentPickerList: [], // 当前可选的项
      currentChangeItem: '', // 当前正在修改的下拉项
      textareaValue: '',
      resultInfoData: [],
      files: {}, // 照片map
      delList: [], // 被删除的列表，需要和后台交互
      showPreview: false,
      reTourCheck: '', // 巡视-1 重新编辑-0
      defaultPickerIndex: 0, // picker默认选中索引
    }
  },
  computed: {
    ...mapGetters(['userData'])
  },
  onLoad(options) {
    this.reTourCheck = options.reTourCheck !== undefined ? options.reTourCheck : '1';
    config.getOptions.then(res => {
      this.baseUrl = res.firstUrl;
    })
    this.objId = options.objId
    this.taskId = options.taskId
    this.taskSiteId = options.taskSiteId
    this.taskSiteName = options.taskSiteName
    this.taskType = options.state
    this.type = options.type
    this.files = JSON.parse(JSON.stringify(fileTemplate));
    if (options.type === 'add') {
      this.isUpdate = false
      this.currentData = JSON.parse(JSON.stringify(infoMap_add))
      this.currentData.hideProps = {
        // 新增业务线  taskid还未带过来，所属站点暂时不能选，
        taskId: options.taskId, //所属工单id    //必填
        siteid: options.taskSiteId, //所属站点
        sitename: options.taskSiteName, //所属站点name
        tourOperId: this.userData.userId, //巡检人ID  必填      userId放进来
        tourOperName: this.userData.userName, //巡检人名称    必填       userName放进来
        tourTim: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'), //巡检时间 必填
        remark: '' //备注
      }
      this.currentData.visibleProps.sitename.value = this.taskSiteName
    } else {
      this.isUpdate = true
      this.currentData = JSON.parse(JSON.stringify(infoMap_update))
      this.currentData.tourInfoProps = {
        tourOperName: {
          title: '巡视人',
          keys: 'tourOperName',
          value: this.userData.userName,
          isRequired: false,
          elementType: 'TEXT'
        }, //设备名称
        tourTim: {
          title: '巡视时间',
          keys: 'tourTim',
          value: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          isRequired: false,
          elementType: 'TEXT'
        } //所属站点名称
      }
      this.$api.todoTaskApi.powerDetail({ objId: this.objId }).then(res => {
        this.currentData.hideProps = {
          taskId: options.taskId, //所属工单id    //必填
          siteid: options.taskSiteId, //所属站点
          sitename: options.taskSiteName, //所属站点
          tourOperId: this.userData.userId, //巡检人ID  必填      userId放进来
          serviceState: res.data.serviceState === null ? 4 : res.data.serviceState, // 第一次巡视（serviceState===null），设备状态默认为更新（4）
          remark: '', //备注
        }
        Object.keys(this.currentData.visibleProps).forEach(key => {
          if (
            this.currentData.visibleProps[key].elementType === 'PICKER' ||
            this.currentData.visibleProps[key].elementType === 'TIMEPICKER'
          ) {
            this.currentData.visibleProps[key].text = res.data[key]
          } else {
            this.currentData.visibleProps[key].value = res.data[key]
          }
          (key === "powerTechType") && (this.currentData.visibleProps[key].value = res.data.powerTechTypeId);
          (key === "accumProducer") && (this.currentData.visibleProps[key].value = res.data.accumProducerId);
        })
        Object.keys(this.currentData.otherProps).forEach(key => {
          this.currentData.otherProps[key] = res.data[key]
        })
        
        this.files = this.files.map((item) => {
          return {
            ...item,
            img: res.data.photoMap[item.type] ? this.baseUrl + res.data.photoMap[item.type]: '',
          }
        })
        this.currentData.visibleProps.sitename.value = this.taskSiteName
        this.currentData.visibleProps.powerLoadCurrent.value = this.reTourCheck === '0' ? res.data.powerLoadCurrent : ''
        this.currentData.visibleProps.accumSumCapacity.value = this.reTourCheck === '0' ? res.data.accumSumCapacity : ''
      })
    }
  },
  
  methods: {
    goBack() {
      if(this.reTourCheck === '0') {
        uni.navigateBack();
      }
      if (this.type === 'add') {
        uni.navigateTo({
          url: `/pages/workBench/todoTask/powerTour/powerTour?taskId=${this.taskId}&taskSiteId=${this.taskSiteId}&state=${this.taskType}&taskSiteName=${this.taskSiteName}`
        })
      } else if (this.type === 'update') {
        uni.navigateTo({
          url: `/pages/workBench/todoTask/powerTour/powerInspect?objId=${this.objId}&taskSiteId=${this.taskSiteId}&state=${this.taskType}&taskId=${this.taskId}&taskSiteName=${this.taskSiteName}`
        })
      }
    },
    formatter(type, val) {
      if (type === 'year') return val + '年'
      if (type === 'month') return val + '月'
      if (type === 'day') return val + '日'
    },
    checkInfo(item) {
      this.currentChangeItem = item.keys
    },
    checkPickerList(optionItem) {
      this.currentChangeItem = optionItem.keys
      if (optionItem.elementType === 'TIMEPICKER') {
        this.currentDate = this.currentData.visibleProps[this.currentChangeItem].text !== ""
          ? new Date(this.currentData.visibleProps[this.currentChangeItem].text)
          : new Date();
        this.showTimePicker = true
      }
      // 下拉选项不为日期类型时，获取可选列表
      else {
        this.showCustomInput = false;
        this.customInput = "";
        // 选项为通信电源型号时，请求传参带入通信电源制造厂商
        if(this.currentChangeItem === "powerModelnumber") {
          if(this.currentData.visibleProps.powerTechType.value === "") {
            Dialog.alert({
              message: '请先选择通信电源制造厂商',
              theme: 'round-button',
            });
            return;
          } else {
            optionItem.optionsParams.pid = this.currentData.visibleProps.powerTechType.value;
          }
        }
        // 选项为配套蓄电池组型号时，请求传参带入配套蓄电池组制造厂商
        else if(this.currentChangeItem === "accumModelnumber") {
          if(this.currentData.visibleProps.accumProducer.value === "") {
            Dialog.alert({
              message: '请先选择配套蓄电池组制造厂商',
              theme: 'round-button',
            });
            return;
          } else {
            optionItem.optionsParams.pid = this.currentData.visibleProps.accumProducer.value;
          }
        }

        if (this.currentChangeItem === 'parRoom') {
          optionItem.optionsParams.pid = this.currentData.hideProps.siteid;
        }
        // 获取可选列表
        this.$api.todoTaskApi
          .selectList_power(optionItem.optionsParams)
          .then(async res => {
            await (this.showPicker = true);
            this.currentPickerList = res.data.map((item, index) => {
              if (item.TOTAL === this.currentData.visibleProps[this.currentChangeItem].text) {
                this.defaultPickerIndex = index;
                this.$refs.picker.setColumnIndex(0, index);
              }
              return {
                text: item.TOTAL,
                value: item.VALUE
              }
            })
            // 如果选项为设通信电源型号/通信电源制造厂商/配套蓄电池组型号/配套蓄电池组制造厂商/整流模块型号时，可自定义
            if (this.currentChangeItem === "powerModelnumber"
              || this.currentChangeItem === "powerTechType"
              || this.currentChangeItem === "accumModelnumber"
              || this.currentChangeItem === "accumProducer"
              || this.currentChangeItem === "powerRectification") {
              this.currentPickerList.push({
                text: "其他",
                value: "other",
              });
              // 如果请求回来的下拉列表不包含当前表单项
              let includes = res.data.some((item, index) => {
                return item.TOTAL === this.currentData.visibleProps[this.currentChangeItem].text;
              });
              if (!includes) {
                // 如果当前表单项的值为空，picker默认选中第一项
                if (this.currentData.visibleProps[this.currentChangeItem].text === "") {
                  this.defaultPickerIndex = 0;
                  this.$refs.picker.setColumnIndex(0, 0);
                  // 如果下拉列表只有’其他‘，则显示自定义输入框
                  if (this.currentPickerList.length === 1) {
                    this.showCustomInput = true;
                  }
                }
                // 如果当前表单项的值不为空，picker默认选至'其他'，自定义值默认填入当前下拉项的值
                else {
                  this.showCustomInput = true;
                  this.defaultPickerIndex = this.currentPickerList.length - 1;
                  this.$refs.picker.setColumnIndex(0, this.currentPickerList.length - 1);
                  this.customInput = this.currentData.visibleProps[this.currentChangeItem].text;
                }
              }
            }
          })
      }
    },
    // 在下拉框中改变选项
    pickerChange (curOption, curValue) {
      this.showCustomInput = curValue.text === '其他';
    },
    // picker确认选择(所有下拉)
    pickerConfirm(selectedOption) {
      if (
        this.currentChangeItem === 'powerBegTim' ||
        this.currentChangeItem === 'accumBegTim'
      ) {
        this.currentData.visibleProps[this.currentChangeItem].text =
          moment(selectedOption).format('YYYY-MM')
        this.showTimePicker = false
      } else {
        if (selectedOption !== undefined) {
          // 如果选择的通信电源制造厂商与上一次不同，通信电源型号清空
          if (this.currentChangeItem === "powerTechType" && selectedOption.value !== this.currentData.visibleProps.powerTechType.value) {
            this.currentData.visibleProps.powerModelnumber.text = "";
            this.currentData.visibleProps.powerModelnumber.value = "";
            this.currentData.hideProps.powerModelnumberCustom = "";
            this.currentData.hideProps.powerTechTypeCustom = "";
          }
          // 如果选择的配套蓄电池组制造厂商与上一次不同，配套蓄电池组型号清空
          else if (this.currentChangeItem === "accumProducer" && selectedOption.value !== this.currentData.visibleProps.accumProducer.value) {
            this.currentData.visibleProps.accumModelnumber.text = "";
            this.currentData.visibleProps.accumModelnumber.value = "";
            this.currentData.hideProps.accumModelnumberCustom = "";
            this.currentData.hideProps.accumProducerCustom = "";
          }
          // 如果选择的通信电源型号与上一次不同，清空自定义通信电源型号
          else if (this.currentChangeItem === "powerModelnumber" && selectedOption.value !== this.currentData.visibleProps.powerModelnumber.value) {
            this.currentData.hideProps.powerModelnumberCustom = "";
          }
          // 如果选择的配套蓄电池组型号与上一次不同，清空自定义配套蓄电池组型号
          else if (this.currentChangeItem === "accumModelnumber" && selectedOption.value !== this.currentData.visibleProps.accumModelnumber.value) {
            this.currentData.hideProps.accumModelnumberCustom = "";
          }
          // 如果选择的整流模块型号与上一次不同，清空自定义整流模块型号
          else if (this.currentChangeItem === "powerRectification" && selectedOption.value !== this.currentData.visibleProps.powerRectification.value) {
            this.currentData.hideProps.powerRectificationCustom = "";
          }
          
          if(selectedOption.text === '其他') {
            this.currentData.visibleProps[this.currentChangeItem].value = selectedOption.value;
            this.currentData.visibleProps[this.currentChangeItem].text = this.customInput;
            this.currentData.hideProps[this.currentChangeItem + "Custom"] = this.customInput;
          } else {
            this.currentData.visibleProps[this.currentChangeItem].value = selectedOption.value;
            this.currentData.visibleProps[this.currentChangeItem].text = selectedOption.text;
          }
        }
        this.showPicker = false;
      }
    },
    // 清空已选
    pickerEmpty(selectedOption) {
      if (
        this.currentChangeItem === 'powerBegTim' ||
        this.currentChangeItem === 'accumBegTim'
      ) {
        this.showTimePicker = false
        this.currentData.visibleProps[this.currentChangeItem].text = ''
      } else {
        this.showPicker = false
        this.currentData.visibleProps[this.currentChangeItem].text = ''
        this.currentData.visibleProps[this.currentChangeItem].value = ''
        if (selectedOption === undefined) {
          selectedOption.text = "";
          selectedOption.value = "";
        }
        // 清空通信电源制造厂商，同时清空通信电源型号
        if (this.currentChangeItem === "powerTechType") {
          this.currentData.visibleProps.powerModelnumber.text = "";
          this.currentData.visibleProps.powerModelnumber.value = "";
          this.currentData.hideProps.powerModelnumberCustom = "";
          this.currentData.hideProps.powerTechTypeCustom = "";
        }
        // 清空配套蓄电池组制造厂商，同时清空配套蓄电池组型号
        else if (this.currentChangeItem === "accumProducer") {
          this.currentData.visibleProps.accumModelnumber.text = "";
          this.currentData.visibleProps.accumModelnumber.value = "";
          this.currentData.hideProps.accumModelnumberCustom = "";
          this.currentData.hideProps.accumProducerCustom = "";
        }
        // 清空自定义通信电源型号
        else if (this.currentChangeItem === "powerModelnumber") {
          this.currentData.hideProps.powerModelnumberCustom = "";
        }
        // 清空自定义配套蓄电池组型号
        else if (this.currentChangeItem === "accumModelnumber") {
          this.currentData.hideProps.accumModelnumberCustom = "";
        }
        // 清空自定义整流模块型号
        else if (this.currentChangeItem === "powerRectification") {
          this.currentData.hideProps.powerRectificationCustom = "";
        }
      }
    },
    // 为输入框时失去焦点采集输入值
    inputBlur(value, item) {
      this.currentChangeItem = item.keys
      this.currentData.visibleProps[this.currentChangeItem].value = value
    },
    imageHandle (imgItem, imgIndex, handleType) {
      if (handleType === 'CHOOSE') {
        this.choosePhoto(imgItem, imgIndex);
      } else if (handleType === 'PREVIEW') {
        this.showPreview = true;
      } else if (handleType === 'DELETE') {
        Dialog.confirm({
          message: `是否确认删除${imgItem.previewName}`
        })
          .then(() => {
            this.$set(this.files, imgIndex, {
              ...this.files[imgIndex],
              raw: null,
              img: ''
            })
            this.delList.includes(imgItem.type) ? null: this.delList.push(imgItem.type);
              console.log(this.delList, "delete")

          })
          .catch(() => {
            // on cancel
          })
      }
    },
    choosePhoto(imgItem, imgIndex) {
      let _this = this;
      wx.chooseImage({
        count: 3,
        sourceType: ["camera"],
        success: (chooseImageRes) => {
          wx.getLocalImgData({
            localId: chooseImageRes.localIds[0].toString(),
            success: function (res) {
                const localData = res.localData;
                let imageBase64 = '';
                if (localData.indexOf('data:image') == 0) {
                    //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
                    imageBase64 = localData;
                } else {
                    //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
                    //此时一个正常的base64图片路径就完美生成赋值到img的src中了
                    imageBase64 = 'data:image/jpeg;base64,' + localData.replace(/\n/g, '');
                }
                
                _this.$set(_this.files, imgIndex, merge(_this.files[imgIndex], {
                   raw: _this.h5_url_to_blob(imageBase64),
                   img: imageBase64
                }));

                
                if (_this.delList.includes(imgItem.type)) {
                  _this.delList = _this.delList.filter(item => {
                    if (item === imgItem.type) {
                      return false;
                    }
                    
                    return true;
                  });
                }
            }
          });
        },
        fail: (error) => {
          console.log(error);
        }
      });
    },
    h5_url_to_blob(url) {
      let arr = url.split(',');
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    // 扫码
    scanQrcode() {
      let _this = this
      wx.scanQRCode({
        desc: 'scanQRCode desc',
        needResult: 1,
        scanType: ['qrCode'],
        success: function (res) {
          _this.currentData.visibleProps.entityid.value = res.resultStr
        },
        error: function (res) {
          console.log('scanQRCode error', res)
        }
      })
    },
    addEquipment() {
      Toast.loading({
        duration:0,
        message: '加载中...',
        forbidClick: true,
      });
      let requestParams = {
        parRoomName: this.currentData.visibleProps.parRoom.text,
        serilanumName: this.currentData.visibleProps.serilanum.text,
        powerTechTypeName: this.currentData.visibleProps.powerTechType.text,
        // equName:   5/9 放入后台处理名称拼接
        //   this.currentData.visibleProps.sitename.value +
        //   this.currentData.visibleProps.parRoom.text +
        //   this.currentData.visibleProps.serilanum.text +
        //   this.currentData.visibleProps.powerTechType.text +
        //   '通信电源',
        // 用户信息
        ...this.userData,
        ...this.currentData.hideProps,
        ...Object.values(this.currentData.visibleProps).reduce((prev, item) => {
          if (item.elementType === "TIMEPICKER" ) {
            prev[item.keys] = item.text;
          } else {
            prev[item.keys] = item.value;
          }
          return prev
        }, {})
      }
      this.$api.getPowerAdd(requestParams).then(res => {
        Toast.clear();
        if(res.code === 0) {
          
          if(res.data === 2) {
            Dialog.confirm({
              message: "该电源已存在，请重新填写",
              showCancelButton: false,
            }).then(() => {});
          }
          
          else {
            Dialog.confirm({
              title: '新增成功',
              showCancelButton: false,
            })
              .then(() => {
                uni.navigateTo({
                  url: `/pages/workBench/todoTask/powerTour/powerTour?taskId=${this.taskId}&taskSiteId=${this.taskSiteId}&state=${this.taskType}&taskSiteName=${this.taskSiteName}`
                })
              })
          }
        }

        else {
          Dialog.alert({
            message: '操作失败',
            theme: 'round-button',
          });
        }
      })
    },
    updateEquipment() {
      Toast.loading({
        duration:0,
        message: '加载中...',
        forbidClick: true,
      });
      let params = {
        reTourCheck: this.reTourCheck, // 巡视-1 重新编辑-0
        objId: this.objId,
        delList: this.delList,
        ...this.userData,
        ...this.currentData.hideProps,
        ...Object.values(this.currentData.visibleProps).reduce((prev, item) => {
          if (item.elementType === "TIMEPICKER") {
            prev[item.keys] = item.text;
          } else {
            prev[item.keys] = item.value;
          }
          return prev
        }, {}),
        ...Object.values(this.currentData.tourInfoProps).reduce(
          (prev, item) => {
            prev[item.keys] = item.value
            return prev
          },
          {}
        ),
        ...this.currentData.otherProps,
        parRoomName: this.currentData.visibleProps.parRoom.text,
        serilanumName: this.currentData.visibleProps.serilanum.text,
        powerTechTypeName: this.currentData.visibleProps.powerTechType.text,
        // equName:   5/9 放入后台处理名称拼接
        //   this.currentData.visibleProps.sitename.value +
        //   this.currentData.visibleProps.parRoom.text +
        //   this.currentData.visibleProps.serilanum.text +
        //   this.currentData.visibleProps.powerTechType.text +
        //   '通信电源',
      }

      let requestParams = {
        params: JSON.stringify(params),
        files: this.files
      }

      let param = new FormData() // 创建form对象
      this.files.forEach((file) => {
        if (file.raw) {
          param.append('files', file.raw, file.name)
        } 
      });
      // param.append('files', this.filesRaw[0], '测试')  // 通过append向form对象添加数据
      param.append('params', requestParams.params) // 添加form表单中其他数据
      // 添加请求头
      let config = {
        headers: { 'Content-Type': 'multipart/form-data',Authorization: uni.getStorageSync('token') || '' }
      }
      let url = "";
      // #ifndef IGW
      url = "/ap/txksh/kosinManage/rest/api/taskCommPow/checkInfoUpdate";
      // #endif
      // #ifdef IGW
      url = `${this.baseUrl}/txksh/kosinManage/rest/api/taskCommPow/checkInfoUpdate`
      // #endif
      
      axios
        .post(
          url,
          param,
          config
        )
        .then(response => {
          Toast.clear();
          
          if(response.data.code === 0) {
            // 如果当前为巡视，且返回data为0，表示重复巡视
            if(this.reTourCheck === '1' && response.data.data === 0) {
              Dialog.confirm({
                message: "该电源已被巡视，请返回重试",
              }).then(() => {
                uni.navigateTo({
                  url: `/pages/workBench/todoTask/powerTour/powerTour?taskId=${this.taskId}&taskSiteId=${this.taskSiteId}&state=${this.taskType}&taskSiteName=${this.taskSiteName}`
                });
              });
            }
  
            // 设备名称重复
            else if(response.data.data === 2) {
              Dialog.confirm({
                message: "该电源已存在，请重新填写",
                showCancelButton: false,
              }).then(() => {});
            }
            
            else {
              Dialog.confirm({
                title: "保存成功",
                showCancelButton: false,
              }).then(() => {
                uni.navigateTo({
                  url: `/pages/workBench/todoTask/powerTour/powerTour?taskId=${this.taskId}&taskSiteId=${this.taskSiteId}&state=${this.taskType}&taskSiteName=${this.taskSiteName}`
                });
              });
            }
          }
          
          else {
            Dialog.alert({
              message: '操作失败',
              theme: 'round-button',
            });
          }
          
        })
    },
    async upload() {
      await this.$refs.ruleForm.validate().then(() => {
        if (!this.isUpdate) {
          // 新增
          this.addEquipment()
        } else {
          this.updateEquipment()
        }
      }).catch(() => {
        Toast('请完善内容');
      })

    }
  }
}
</script>

<style scoped lang="scss">
.complete-wrap {
  min-height: 100vh;
  background-color: #f8f8f8;
  .header {
    position: sticky;
    top: 0;
    z-index: 9;
  }

  .van-preview-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    .van-swipe {
      width: 100%;
      height: 60%;
    }
    img {
      height: 90%;
    }
  }

  .main-container {
    //width: 100vw;
    //height: 100vh;
    padding: px2vh(30) px2vw(30) px2vh(90) px2vw(30);
    /deep/.van-field__label,
    /deep/.van-field__control:read-only,
    /deep/.van-field__body .van-field__control{
      font-size: px2vw(42);
    }
    /deep/.van-field__label {
      width: 10em;
    }
    .base-info-container,
    .result-info-container {
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #ffffff;
    }

    .result-info-container {
      margin-top: px2vh(30);
    }

    .plate-title {
      margin-top: px2vh(30);
      margin-bottom: px2vh(27);
    }

    .plate-title-2 {
      margin-top: px2vh(60);
      margin-bottom: px2vh(27);
    }

    .remark-info-container {
      padding: px2vh(70) px2vw(50);
      font-size: px2vw(42);
      color: #666666;
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #ffffff;
      margin-top: px2vh(30);
      .remark-wrap {
        background-color: #fafafa;
        padding: px2vh(41) px2vw(56) px2vh(77) px2vw(55);
        border-radius: px2vw(20);
        .remark-text {
          height: px2vh(150);
        }
      }
    }

    .patrol-info-container {
      padding: px2vh(70) px2vw(50);
      font-size: px2vw(42);
      color: #666666;
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #ffffff;

      /deep/.van-radio {
        margin-right: px2vw(139.5);
      }

      .image-wrap {
        width: 100%;
        display: flex;
        img {
          width: px2vw(215);
          height: px2vw(215);
          margin-right: px2vw(40);
          border-radius: px2vw(6);
        }

        .image-list {
          width: 100%;
          display: flex;
          .upload-button {
            width: px2vw(215);
            height: px2vw(215);
            background-size: cover;
            margin-right: px2vw(40);
            position: relative;
            .delete-icon {
              position: absolute;
              top: px2vw(-20);
              right: px2vw(-20);
              width: px2vw(40);
              height: px2vw(40);
              background-color: rgba(0, 0, 0, 0.7);
              border-radius: 50%;
              color: #fff;
              display: flex;
              justify-content: center;
              align-items: center;
            }
          }
        }
      }
    }

    /deep/.van-button {
      margin-top: px2vh(70);
      height: px2vh(120);
      color: #fff;
      background-color: #417adc;
      border: 1px solid #417adc;
      border-radius: px2vh(60);
    }
    /deep/.van-uploader__upload-icon {
      text-align: center;
    }
    .van-popup {
      background-color: #eee;
      .van-cell {
        position: absolute;
        bottom: 0;
        border-top: 4px solid #eee;
        z-index: 3;
      }
    }
  }
}
</style>